// middleware/auth.go
package middleware

import (
	"strings"

	"gorm_project/services"
	"gorm_project/utils"

	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
)

func AuthMiddleware(authService *services.AuthService) gin.HandlerFunc {
	return func(c *gin.Context) {
		authHeader := c.GetHeader("Authorization")
		if authHeader == "" {
			utils.Unauthorized(c, "缺少认证令牌")
			c.Abort()
			return
		}

		parts := strings.SplitN(authHeader, " ", 2)
		if !(len(parts) == 2 && parts[0] == "Bearer") {
			utils.Unauthorized(c, "令牌格式错误")
			c.Abort()
			return
		}

		token, err := authService.ValidateToken(parts[1])
		if err != nil || !token.Valid {
			utils.Unauthorized(c, "令牌无效")
			c.Abort()
			return
		}

		claims, ok := token.Claims.(jwt.MapClaims)
		if !ok {
			utils.Unauthorized(c, "令牌解析失败")
			c.Abort()
			return
		}

		c.Set("user", claims)
		c.Next()
	}
}

func AdminMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		if claims, exists := c.Get("user"); exists {
			if userClaims, ok := claims.(jwt.MapClaims); ok {
				if role, ok := userClaims["role"].(string); ok && role == "admin" {
					c.Next()
					return
				}
			}
		}

		utils.Unauthorized(c, "需要管理员权限")
		c.Abort()
	}
}
